﻿#pragma execution_character_set("utf-8")
#include "qqmain.h"
#include "ui_qqmain.h"

QQMain::QQMain(HttpClient *httpClient,WebSocketClient* webSocketClient,FileOperator* fileOperator,SQLiteUtil* sQLiteUtil,const QString &email,const QString &username,const bool &isDownLoad,const QString &sign,QWidget *parent) :
    QWidget(parent)
    , ui(new Ui::QQMain)
    , email(email)
    , httpClient(httpClient)
    , webSocketClient(webSocketClient)
    , fileOperator(fileOperator)
    , sQLiteUtil(sQLiteUtil)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);    //窗口close后释放内存
    setWindowFlags(Qt::FramelessWindowHint);    //隐藏标题栏（无边框）
    setAttribute(Qt::WA_StyledBackground);    //启用样式背景绘制
    setAttribute(Qt::WA_TranslucentBackground);    //背景透明
    setAttribute(Qt::WA_Hover);

    relationMenu=new AddRelation_menu(this);
    relationMenu->hide();

    //设置用户名字
    ui->username_LB->setText(username);
    //设置用户的签名
    ui->signature_LB->setText(sign);

    loadHttpComponentRespond();
    loadSocketComponentRespond();
    loadBaseComponentRespond();

    if(isDownLoad)//下载头像
        this->httpClient->get(headImgUrl+QString("&&email=%1&&temporary=0").arg(email));
    else
    {//设置头像
        QFile file(QString("./accountData/%1/headImg/head.png").arg(this->email));
        if(file.exists()&&file.size()>0)
            updateHeadImg();
        else
            this->httpClient->get(headImgUrl+QString("&&email=%1&&temporary=0").arg(email));
    }

    //获取用户的好友信息
    this->httpClient->post("/App/friends?email="+email);
    {
        QVariantMap resultMap=sQLiteUtil->selectOneMessageRecentCreateTime();
        QString lastTime;
        if(!resultMap.isEmpty()){
            lastTime=resultMap["createTime"].toString();
        }
        else
        {
            lastTime="0";
        }
        //获取离线信息
        this->httpClient->post(QString("App/messages?email=%1&&lastTime=%2").arg(email,lastTime));
    }


    //设置主窗口的阴影
    createShadow();
}

QQMain::~QQMain()
{
    webSocketClient->deleteLater();
    httpClient->deleteLater();
    delete fileOperator;
    delete sQLiteUtil;
    relationMenu->deleteLater();
    searchFriend->deleteLater();
    delete ui;
}

bool QQMain::event(QEvent *event)
{
    if (event->type() == QEvent::HoverMove) {
        QHoverEvent *hoverEvent = static_cast<QHoverEvent *>(event);
        QMouseEvent mouseEvent(QEvent::MouseMove, hoverEvent->pos(),
                               Qt::NoButton, Qt::NoButton, Qt::NoModifier);
        mouseMoveEvent(&mouseEvent);
    }

    return QWidget::event(event);
}

void QQMain::leaveEvent(QEvent *event)//鼠标离开窗口时触发
{
    m_bIsPressed = false;
    m_bIsResizing = false;
    QWidget::leaveEvent(event);
}

void QQMain::mousePressEvent(QMouseEvent *event)//鼠标在窗口按压时触发
{
    if (event->button() == Qt::LeftButton) {
        hideMenu();
        m_bIsPressed = true;
        m_pressPoint = event->globalPos();//记录鼠标按压时在桌面的位置
    }
    return QWidget::mousePressEvent(event);
}

void QQMain::mouseMoveEvent(QMouseEvent *event)//鼠标在窗口移动时触发
{
    if (m_bIsPressed) {
        if (m_bIsResizing) {//调整窗口大小
            m_movePoint = event->globalPos() - m_pressPoint;//获取鼠标位置相对鼠标按压位置的移动量
            m_pressPoint+=m_movePoint;//按压位置追踪鼠标

        } else {//移动窗口
            QPoint point = event->globalPos() - m_pressPoint;
            move(pos() + point);
            m_pressPoint = event->globalPos();
        }
    }

    if (windowState() != Qt::WindowMaximized) {
        updateRegion(event);
    }
    QWidget::mouseMoveEvent(event);
}

void QQMain::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_bIsPressed = false;
        m_bIsResizing = false;
    }
    QWidget::mouseReleaseEvent(event);
}

void QQMain::updateRegion(QMouseEvent *event)
{
    QRect mainRect = geometry();//获取当前窗口的几何信息（位置和大小）。

    //计算出鼠标指针相对于窗口四个边的距离
    int marginTop = event->globalY() - mainRect.y();//获取鼠标离上边框的距离
    int marginBottom = mainRect.y() + mainRect.height() - event->globalY();//获取鼠标离下边框的距离
    int marginLeft = event->globalX() - mainRect.x();//获取鼠标离左边框的距离
    int marginRight = mainRect.x() + mainRect.width() - event->globalX();//获取鼠标离右边框的距离

    //设置鼠标在窗口的边界时的鼠标指针的变化
    if (!m_bIsResizing) {
        if ( (marginRight >= MARGIN_MIN_SIZE && marginRight <= MARGIN_MAX_SIZE)
            && ((marginBottom <= MARGIN_MAX_SIZE) && marginBottom >= MARGIN_MIN_SIZE) ) {
            m_direction = Direction::BOTTOMRIGHT;//右下
            setCursor(Qt::SizeFDiagCursor);
        } else if ( (marginTop >= MARGIN_MIN_SIZE && marginTop <= MARGIN_MAX_SIZE)
                   && (marginRight >= MARGIN_MIN_SIZE && marginRight <= MARGIN_MAX_SIZE)) {
            m_direction = Direction::TOPRIGHT;//右上
            setCursor(Qt::SizeBDiagCursor);
        } else if ( (marginLeft >= MARGIN_MIN_SIZE && marginLeft <= MARGIN_MAX_SIZE)
                   && (marginTop >= MARGIN_MIN_SIZE && marginTop <= MARGIN_MAX_SIZE) ) {
            m_direction = Direction::TOPLEFT;//左上
            setCursor(Qt::SizeFDiagCursor);
        } else if ( (marginLeft >= MARGIN_MIN_SIZE && marginLeft <= MARGIN_MAX_SIZE)
                   && (marginBottom >= MARGIN_MIN_SIZE && marginBottom <= MARGIN_MAX_SIZE)) {
            m_direction = Direction::BOTTOMLEFT;//左下
            setCursor(Qt::SizeBDiagCursor);
        } else if (marginBottom <= MARGIN_MAX_SIZE && marginBottom >= MARGIN_MIN_SIZE) {
            m_direction = Direction::DOWN;//下
            setCursor(Qt::SizeVerCursor);
        } else if (marginLeft <= MARGIN_MAX_SIZE - 1 && marginLeft >= MARGIN_MIN_SIZE - 1) {
            m_direction = Direction::LEFT;//左
            setCursor(Qt::SizeHorCursor);
        } else if (marginRight <= MARGIN_MAX_SIZE && marginRight >= MARGIN_MIN_SIZE) {
            m_direction = Direction::RIGHT;//右
            setCursor(Qt::SizeHorCursor);
        } else if (marginTop <= MARGIN_MAX_SIZE && marginTop >= MARGIN_MIN_SIZE) {
            m_direction = Direction::UP;//上
            setCursor(Qt::SizeVerCursor);
        } else {//鼠标指针不在窗口的边界,那么鼠标指针恢复默认
            if (!m_bIsPressed) {
                setCursor(Qt::ArrowCursor);
            }
        }
    }

    if (m_direction!=Direction::NONE) {
        m_bIsResizing = true;
        resizeRegion();
    }
}

void QQMain::resizeRegion()
{
    if(!m_bIsPressed){
        m_bIsResizing = false;
        m_direction = Direction::NONE;
        return ;
    }
    QRect rect = geometry();
    qDebug()<<"one:"<<rect;
    switch (m_direction)
    {
        case Direction::BOTTOMRIGHT://右下
        {
            extendRight(rect);
            extendDown(rect);
        }
        break;
        case Direction::TOPRIGHT://右上
        {
            extendRight(rect);
            extendTop(rect);
        }
        break;
        case Direction::TOPLEFT://左上
        {
            extendLeft(rect);
            extendTop(rect);
        }
        break;
        case Direction::BOTTOMLEFT://左下
        {
            extendLeft(rect);
            extendDown(rect);
        }
        break;
        case Direction::RIGHT://右
        {
            extendRight(rect);
        }
        break;
        case Direction::DOWN://下
        {
            extendDown(rect);
        }
        break;
        case Direction::LEFT://左
        {
            extendLeft(rect);
        }
        break;
        case Direction::UP://上
        {
            extendTop(rect);
        }
    }
    rect.setWidth(qBound(minimumWidth(), rect.width(), maximumWidth()));
    rect.setHeight(qBound(minimumHeight(), rect.height(), maximumHeight()));
    qDebug()<<"second:"<<rect;
    setGeometry(rect);
}

void QQMain::extendLeft(QRect &rect){
    int x=m_pressPoint.x();//鼠标的位置
    if(x<rect.x()&&rect.width()==maximumWidth()||x>rect.x()&&rect.width()==minimumWidth()){
        return;
    }
    else{
        rect.adjust(m_movePoint.x(), 0, 0, 0);
    }
}

void QQMain::extendRight(QRect &rect){
    int x=m_pressPoint.x();
    if(x>rect.x()+rect.width()&&rect.width()==maximumWidth()||x<rect.x()+rect.width()&&rect.width()==minimumWidth()){
        return;
    }
    else{
        rect.adjust(0, 0, m_movePoint.x(), 0);
    }
}

void QQMain::extendTop(QRect &rect){
    int y=m_pressPoint.y();
    if(y<rect.y()&&rect.height()==maximumHeight()||y>rect.y()&&rect.height()==minimumHeight()){
        return ;
    }
    else{
        rect.adjust(0, m_movePoint.y(), 0, 0);
    }
}

void QQMain::extendDown(QRect &rect){
    int y=m_pressPoint.y();
    if(y>rect.y()+rect.height()&&rect.height()==maximumHeight()||y<rect.y()+rect.height()&&rect.height()==minimumHeight()){
        return;
    }
    else{
        rect.adjust(0, 0, 0, m_movePoint.y());
    }
}

void QQMain::createShadow(){
    QGraphicsDropShadowEffect *mainShadow = new QGraphicsDropShadowEffect(this);
    mainShadow->setOffset(0,0); // 设置阴影偏移量
    mainShadow->setBlurRadius(13); // 设置阴影模糊半径
    mainShadow->setColor(QColor(130,130,130)); // 设置阴影颜色（RGBA）
    ui->QQMain_content_WT->setGraphicsEffect(mainShadow);
}


void QQMain::resizeEvent(QResizeEvent *event){
    QSize newSize=event->size();
    emit resizeWidth(newSize.width());
//    return QWidget::resizeEvent(event);
}

void QQMain::loadHttpComponentRespond(){
    connect(httpClient,&HttpClient::finished,[this](const QUrl &url, const QByteArray &data){
        QString URL=url.toString();
        if(URL.contains("sendMessage")){//验证自己的信息是否发送成功
            QVariantMap msgMap=this->fileOperator->parseJsonObject(data);
            QString msgId=msgMap["msgId"].toString();
            msgMap.remove("msgId");
            msgMap["isSend"]="isSend+1";
            sQLiteUtil->updateMessage(msgMap,msgId);//更新状态
            msgMap.clear();
            msgMap=sQLiteUtil->selectOneSelfInfo(msgId);
            QString friend_id=msgMap["friendId"].toString();
            msgMap.remove("friendId");
            updateInfoPage(msgMap,friend_id);
        }
        else if(URL.contains("get_head_img"))//设置请求回来的图片
        {
            QMap<QString,QString> urlMap=this->fileOperator->getQueryParamsFromUrl(URL,"&&");
            if(!urlMap["temporary"].isNull()&&urlMap["temporary"]=="0")
            {
                if(urlMap["email"]==this->email)//设置自己的图片
                {
                    QFile file(QString("./accountData/%1/headImg/head.png").arg(this->email));
                    if(data!=nullptr)
                        this->fileOperator->writeFile(file,data);//将头像图片保存
                    if(file.exists()&&file.size()>0)
                        updateHeadImg();
                }
                else
                {
                    QFile file(QString("./accountData/Res/%1/headImg/head.png").arg(urlMap["email"]));
                    if(data!=nullptr)
                        this->fileOperator->writeFile(file,data);//将头像图片保存
                    if(file.exists()&&file.size()>0)
                    {
                        QString _email=urlMap["email"];
                        updateFriendsHImg(_email);
                        updateInfoListHImg(_email);
                    }

                }
            }
        }
        else if(URL.contains("friends"))
        {
            QVariantList variantList=this->fileOperator->parseJsonArray(data);
            for(auto &it:variantList)//遍历每个好友的信息
            {
                QVariantMap map=it.toMap();
                updateFriendInfo(map);
                variantList.pop_front();
            }
            setFriendList();
            loadSearchFriendRespond();
        }
        else if(URL.contains("messages")){//接受离线信息
            QVariantList list=this->fileOperator->parseJsonArray(data);
            if(!list.isEmpty())
            {
                for(auto &item:list)//遍历每条消息
                {
                    QVariantMap msgMap=item.toMap();
                    saveMessage(msgMap);
                }
            }
            setInfoPage();
        }
    });

    connect(httpClient,&HttpClient::errorOccurred,[this](const QUrl &url,const QNetworkReply::NetworkError &error){
        QString URL=url.toString();
        if(URL.contains("friends")){
            if(ui->friends_WT->layout()->count()-1==0)
                setFriendList();
            if(searchFriend==nullptr)
                loadSearchFriendRespond();
        }
        else if(URL.contains("messages")){
            if(ui->info_page_WT->layout()->count()-1==0)
                setInfoPage();
        }
    });
}

void QQMain::loadSocketComponentRespond(){
    connect(webSocketClient,&WebSocketClient::sigRecvTextMsg,[this](const QString &data){
        QVariantMap msgMap=this->fileOperator->parseJsonObject(data.toUtf8());
        if(!msgMap.isEmpty()){
            if(msgMap.contains("msgId"))
            {
                //处理收到的好友信息
                //msgId,sender,receiver,type,content,createTime;
                msgMap.remove("msgId");
                msgMap.remove("receiver");
                QString sender=msgMap["sender"].toString();
                msgMap.remove("sender");
                updateInfoPage(msgMap,sender);//更新信息列表
            }
            else if(msgMap.contains("friendId"))
            {
                if(msgMap.contains("alterTime")){
                    //处理申请同意
                    //friendId,userName,sign,alterTime,buildTime;
                    QString buildTime=msgMap["buildTime"].toString();
                    msgMap.remove("buildTime");
                    sQLiteUtil->insertFriend(msgMap);//将好友的信息保存在数据库中
                    QString friendId=msgMap["friendId"].toString();
                    QString username=msgMap["userName"].toString();
                    msgMap.clear();
                    updateFriend(friendId,QString("我是%1").arg(username),buildTime);
                    emit updateFriendList(friendId,username);
                    //获取好友的头像
                    httpClient->get(headImgUrl+QString("&&email=%1&&temporary=0").arg(friendId));
                }
                else
                {
                    //处理好友申请
                    //friendId,userName,content,buildTime
                    QString friendId=msgMap["friendId"].toString();
                    if(sQLiteUtil->selectOneApplicationIsExist(friendId)){
                        msgMap.remove("friendId");
                        sQLiteUtil->updateApplication(msgMap,friendId);
                    }
                    else{
                        msgMap["status"]=0;
                        sQLiteUtil->insertApplication(msgMap);//将申请信息保存在数据库中
                    }
                    emit updateApplication(friendId);
                }
            }
        }
    });
}
void QQMain::loadBaseComponentRespond(){

    connect(ui->minimize_BT,&QPushButton::clicked,[this](){
        this->hide();
    });

    connect(ui->close_BT,&QPushButton::clicked,[this](){
        this->close();
        emit quit();
    });

    connect(ui->info_BT,&QPushButton::clicked,[this](){
        ui->main_SWT->setCurrentIndex(0);
        ui->info_WT->setStyleSheet("#info_WT{border-bottom:2px solid black;}");
        ui->space_WT->setStyleSheet("#space_WT{border:none;}");
        ui->friend_WT->setStyleSheet("#friend_WT{border:none}");
    });

    connect(ui->space_BT,&QPushButton::clicked,[this](){
        ui->main_SWT->setCurrentIndex(1);
        ui->info_WT->setStyleSheet("#info_WT{border:none;}");
        ui->space_WT->setStyleSheet("#space_WT{border-bottom:2px solid black;}");
        ui->friend_WT->setStyleSheet("#friend_WT{border:none;}");
    });

    connect(ui->friend_BT,&QPushButton::clicked,[this](){
        ui->main_SWT->setCurrentIndex(2);
        ui->info_WT->setStyleSheet("#info_WT{border:none;}");
        ui->space_WT->setStyleSheet("#space_WT{border:none;}");
        ui->friend_WT->setStyleSheet("#friend_WT{border-bottom:2px solid black;}");
    });

    connect(ui->friends_BT,&QPushButton::clicked,[this](){
        ui->friend_SWT->setCurrentIndex(0);
        ui->friends_BT->setStyleSheet("background-color:rgb(243, 245, 248);");
        ui->groups_BT->setStyleSheet("#groups_BT:hover{color:black;}");
    });

    connect(ui->groups_BT,&QPushButton::clicked,[this](){
        ui->friend_SWT->setCurrentIndex(1);
        ui->friends_BT->setStyleSheet("#friends_BT:hover{color:black;}");
        ui->groups_BT->setStyleSheet("background-color:rgb(243, 245, 248);");
    });

    connect(ui->add_relation,&QPushButton::clicked,[this](){
        if(!relationMenu->isVisible())
        {
            relationMenu->move(QPoint(width()-180,280));
            relationMenu->show();
            relationMenu->setFocus();
            ui->add_relation->setStyleSheet(R"(
                #add_relation{
                    border:none;
                    border-image:url(':/background/imagesRes/add_relation.png') 0 0 0 0 stretch stretch;
                    background-color:rgb(241, 241, 241);
                }
)");
        }
    });

    connect(relationMenu,&AddRelation_menu::onHide,[this](){
        ui->add_relation->setStyleSheet(R"(
            #add_relation{
                border:none;
                border-image:url(':/background/imagesRes/add_relation.png') 0 0 0 0 stretch stretch;
            }
            #add_relation:hover{
                background-color:rgb(241, 241, 241);
            }
        )");
    });

    connect(relationMenu,&AddRelation_menu::showSearchFriend,this,&QQMain::showSearchFriendWidget);

    connect(ui->addFriend_BT,&QPushButton::clicked,this,&QQMain::showSearchFriendWidget);

}

void QQMain::loadSearchFriendRespond(){
    searchFriend=new SearchFriend(httpClient,fileOperator,sQLiteUtil,email,ui->username_LB->text());

    connect(searchFriend,&SearchFriend::closeClicked,[this](){
        //屏幕居中显示
        QPoint screenCenter = QApplication::primaryScreen()->geometry().center();
        QPoint windowSize(searchFriend->minimumWidth()/2,searchFriend->minimumHeight()/2);
        searchFriend->move(screenCenter-windowSize);
    });

    connect(searchFriend,&SearchFriend::updateFriend,this,&QQMain::updateFriend);
    connect(this,&QQMain::updateApplication,searchFriend,&SearchFriend::updateApplication);
    connect(this,&QQMain::updateFriendList,searchFriend,&SearchFriend::updateFriendList);
}

void QQMain::infoItemClick(Info_item* newItem){
    static Info_item* lastItem=nullptr;
    newItem->setClickStyle();
    if (lastItem == nullptr)
        lastItem = newItem;
    else if (lastItem != newItem)
    {
        lastItem->setNormalStyle();
        lastItem = newItem;
    }
}
void QQMain::friendItemClick(FriendItem* newItem){
    static FriendItem* lastItem=nullptr;
    newItem->setClickStyle();
    if (lastItem == nullptr)
        lastItem = newItem;
    else if (lastItem != newItem)
    {
        lastItem->setNormalStyle();
        lastItem = newItem;
    }
}
void QQMain::setInfoPage(){
    QList<QVariantMap> list=sQLiteUtil->selectAllSessionNewInfo();
    QVBoxLayout* info_page=(QVBoxLayout*)ui->info_page_WT->layout();
    if(info_page->count()-1>0){
        for(int i=0;i<info_page->count()-1;i++){
            info_page->itemAt(0)->widget()->deleteLater();
        }
    }
    for(auto &map:list){
        QString friendId=map["friendId"].toString();
        QString name=getUserName(map);
        map.remove("friendId");
        map.remove("userName");
        map.remove("noteName");
        Info_item* item=createInfoItem(friendId,name,map);
        info_page->insertWidget(0,item);
        map.clear();
        list.pop_front();
    }
}
void QQMain::updateHeadImg(){
    if(QFile::exists(QString("./accountData/%1/headImg/head.png").arg(this->email))){
        ui->userImg_BT->setStyleSheet(QString("\
            QPushButton{\
                border:1px solid black;\
                border-radius:35px;\
                border-image: url('./accountData/%1/headImg/head.png') 0 0 0 0 stretch stretch;\
            }\
        ").arg(this->email));
    }
}
void QQMain::setFriendList(){//初始化好友列表
    QList<QVariantMap> friendList=sQLiteUtil->selectAllFriendInfoList();
    ((QVBoxLayout*)ui->friends_WT->layout())->addStretch();
    for(auto &map:friendList)
    {
        insertFriendList(map["friendId"].toString(),map,OrientType::BACK);
        map.clear();
        friendList.pop_front();
    }
}
void QQMain::hideMenu(){
    if(relationMenu->isVisible())
    {
        ui->add_relation->setStyleSheet(R"(
            #add_relation{
                border:none;
                border-image:url(':/background/imagesRes/add_relation.png') 0 0 0 0 stretch stretch;
            }
            #add_relation:hover{
                background-color:rgb(241, 241, 241);
            }
)");
        relationMenu->hide();
    }
}

//更新信息列表和创建信息
void QQMain::updateInfoPage(QVariantMap &msgMap,const QString &msger){
    QVBoxLayout* info_page=(QVBoxLayout*)ui->info_page_WT->layout();
    for(int i=0;i<info_page->count()-1;i++)
    {
        Info_item* item=(Info_item*)info_page->itemAt(i)->widget();
        if(item->getEmail()==msger)
        {
            item->setNewInfo(getMsgForType(msgMap),fileOperator->formatMessageTime(msgMap["createTime"].toLongLong()));
            if((Info_item*)(info_page->itemAt(0)->widget())!=item)//将消息置顶
            {
                info_page->removeWidget(item);
                info_page->insertWidget(0,item);
            }
            return ;
        }
    }
    QVariantMap resultMap=this->sQLiteUtil->selectOneFriendUsername(msger);
    Info_item* item=createInfoItem(msger,getUserName(resultMap),msgMap);
    info_page->insertWidget(0,item);
}

Info_item* QQMain::createInfoItem(const QString &email,const QString &username,QVariantMap &msgMap){//创建一个信息项
    Info_item* item=new Info_item(email,username,getMsgForType(msgMap),fileOperator->formatMessageTime(msgMap["createTime"].toLongLong()),this->width());

    connect(this,&QQMain::resizeWidth,item,&Info_item::resizeWidth);
    connect(item,&Info_item::clicked,this,&QQMain::infoItemClick);
    connect(item,&Info_item::showComm,[this](QString _email,QString name,QString message){
        emit showComm(_email,name,message);
    });
    return item;
}

void QQMain::showSearchFriendWidget(){
    if(searchFriend!=nullptr)
        if(searchFriend->isMinimized())
            searchFriend->showNormal();
        else
            searchFriend->show();
}

QString QQMain::getMsgForType(QVariantMap &map){
    QString type=map["type"].toString();
    if(type=="text"||type=="apply")
        return map["content"].toString();
    else
        if(map["content"].isNull()||map["content"].toString().isEmpty())
            return "[图片]";
        else
            return "[文件]";
}
QString QQMain::getUserName(QVariantMap &map){
    if(map["noteName"].isNull()||map["notename"].toString().isEmpty())
        return map["userName"].toString();
    else
        return map["noteName"].toString();
}

void QQMain::getRecentMessage(const QString &email,const QString &name){
    QVariantMap resultMap=sQLiteUtil->selectOneMessageRecentContent(email);
    QString text="";
    if(!resultMap.isEmpty())
        text=getMsgForType(resultMap);
    emit showComm(email,name,text);
}

void QQMain::updateFriendsHImg(QString &email){
    QVBoxLayout* friendList= qobject_cast<QVBoxLayout*>(ui->friends_WT->layout());
    if(friendList->count()-1>0){
        for(int i=0;i<friendList->count()-1;i++){
            FriendItem* item=qobject_cast<FriendItem*>(friendList->itemAt(i)->widget());
            if(item->getEmail()==email){
                item->updateHeadImg();
                break;
            }
        }
    }
}
void QQMain::updateInfoListHImg(QString &email){
    QVBoxLayout* infoList=qobject_cast<QVBoxLayout*>(ui->info_page_WT->layout());
    if(infoList->count()-1>0){
        for(int i=0;i<infoList->count()-1;i++){
            Info_item* item=qobject_cast<Info_item*>(infoList->itemAt(i)->widget());
            if(item->getEmail()==email){
                item->updateHeadImg();
                break;
            }
        }
    }
}
void QQMain::updateFriendInfo(QVariantMap &map){
    QString friend_id = map["friendId"].toString();
    if(sQLiteUtil->selectOneFriendIsExist(friend_id))
    {//记录存在
        QVariantMap resultMap = sQLiteUtil->selectOneFriendAlterTime(friend_id);
        if(resultMap["alterTime"]!=map["alterTime"])
        {//是否更新记录
            httpClient->get(headImgUrl+QString("&&email=%1&&temporary=0").arg(friend_id));//下载用户的头像
            sQLiteUtil->updateFriendBind(map,friend_id);//更新用户的信息
        }
    }
    else//记录不存在
    {
        sQLiteUtil->insertFriend(map);
    }
    if(!QFile::exists(QString("./accountData/Res/%1/headImg/head.png").arg(friend_id)))
    {//查看头像图片是否丢失，否则下载
        httpClient->get(headImgUrl+QString("&&email=%1&&temporary=0").arg(friend_id));
    }
}

void QQMain::saveMessage(QVariantMap &map){
    //将信息插入数据库中
    QString sender=map["sender"].toString();
    QString receiver=map["receiver"].toString();
    map.remove("sender");
    map.remove("receiver");
    if(sender==this->email)
        map["isSelf"]=1;
    else{
        map["isSelf"]=0;
    }
    map["isSend"]=1;
    sQLiteUtil->insertMessage(map);//插入数据库中
    map.remove("isSelf");
    {
        QVariantMap insertMap;
        if(sender!=this->email){
            insertMap["friendId"]=sender;
        }
        else{
            insertMap["friendId"]=receiver;
        }
        insertMap["msgId"]=map["msgId"];
        sQLiteUtil->insertSession(insertMap);//插入数据库中
    }
    if(map["type"].toString()=="png"){//下载图片
        httpClient->downLoadFile(QString("/App/download?type=image&&email=%1&&fileName=%2&&suffix=%3").arg(sender,map["msgId"].toString(),map["type"].toString()));
    }
}

void QQMain::insertFriendList(const QString &email,QVariantMap &map,const OrientType &type){
    FriendItem* frienditem=new FriendItem(email,getUserName(map),map["sign"].toString());
    connect(frienditem,&FriendItem::clicked,this,&QQMain::friendItemClick);
    connect(frienditem,&FriendItem::showComm,this,&QQMain::getRecentMessage);
    insertWidget((QBoxLayout*)ui->friends_WT->layout(),frienditem,type);
}

void QQMain::insertInfoList(const QString &email,const QString &username,QVariantMap &map,const OrientType &type){
    Info_item* item=createInfoItem(email,username,map);
    insertWidget((QBoxLayout*)ui->info_page_WT->layout(),item,type);
}
void QQMain::updateFriend(const QString &email,const QString &content,const QString &createTime){
    QVariantMap map=sQLiteUtil->selectOneFriendInfo(email);//userName,noteName,sign
    insertFriendList(email,map,OrientType::FRONT);//插入好友列表
    QString username=getUserName(map);
    map.clear();
    QString uuid=QUuid::createUuid().toString(QUuid::WithoutBraces).replace("-","");
    map["msgId"]=uuid;
    map["isSelf"]=0;
    map["isSend"]=1;
    map["type"]="text";
    map["content"]=content;
    map["createTime"]=createTime;
    insertInfoList(email,username,map,OrientType::FRONT);//插入信息列表
    sQLiteUtil->insertMessage(map);//插入消息到数据库中
    map.clear();
    map["friendId"]=email;
    map["msgId"]=uuid;
    sQLiteUtil->insertSession(map);//插入消息到数据库中
}
